import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { setRanking } from "@/store/ranking/rankingAPI";
import { changeCreate, getRankingAsync } from "@/store/ranking/rankingSlice";
import { Form, Input, Modal, Select } from "antd";
import { ReactElement, useEffect, useState } from "react";
import { shallowEqual } from "react-redux";

export default function Create(): ReactElement<typeof Modal, "div"> {
  const [loading, setLoading] = useState<boolean>(false);
  const { create, params } = useAppSelector(
    (state) => state.ranking,
    shallowEqual
  );
  const {
    config: { data: { data: { rank_type_map, rank_gear_map } = {} } = {} } = {},
  } = useAppSelector((state) => state.app, shallowEqual);
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();

  const handleClose = () => {
    dispatch(changeCreate({ open: false }));
    form.resetFields();
  };
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      setRanking(values)
        .then(() => {
          handleClose();
          if (params.rank_type) {
            dispatch(getRankingAsync({ ...params }));
          }
        })
        .finally(() => {
          setLoading(false);
        });
    } catch (err) {
      console.error("校验不通过");
    }
  };

  useEffect(() => {
    if (create.type === "update" && create.open) {
      form.setFieldsValue(create.record);
    }
  }, [create]);

  return (
    <Modal
      open={create.open}
      title={create.type === "create" ? "创建" : "编辑"}
      onCancel={handleClose}
      onOk={handleOk}
      confirmLoading={loading}
    >
      <Form form={form}>
        <Form.Item
          name="rank_type"
          label="榜单类型"
          rules={[{ required: true, message: "必填" }]}
        >
          <Select options={rank_type_map} disabled={create.type === 'update'} />
        </Form.Item>
        <Form.Item
          name="gear_id"
          label="档位id"
          rules={[{ required: true, message: "必填" }]}
        >
          <Select disabled={create.type === 'update'}
            options={rank_gear_map}
          />
        </Form.Item>
        <Form.Item
          name="rank_reward"
          label="奖励值"
          rules={[{ required: true, message: "必填" }]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}
